package com.xnyzc.lhy.resource.controller.cp;

import com.alibaba.fastjson.JSONObject;
import com.xnyzc.lhy.resource.common.cp.dto.SingleQueryParam;
import com.xnyzc.lhy.resource.common.cp.dto.SingleTradeResult;
import com.xnyzc.lhy.resource.common.cp.dto.TransactionInfo;
import com.xnyzc.lhy.resource.common.cp.exception.CPException;
import com.xnyzc.lhy.resource.service.cp.ITradeService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 银联相关接口
 * </p>
 *
 * @author haoyfa
 * @since 2019-11-13
 */
@RestController
@RequestMapping("/cp")
@Slf4j
public class ChinaPayController {

    @Autowired
    private ITradeService singleTradeService;

    /**
     * 单笔代付
     */
    @ApiOperation(value = "单笔代付", notes = "单笔代付")
    @PostMapping(value = "singleTrade")
    public JSONObject singleTrade(@ApiParam(name = "transactionInfo", value = "单笔代付交易信息") @RequestBody TransactionInfo transactionInfo) {
        SingleTradeResult singleTradeResult = null;
        try {
            singleTradeResult = singleTradeService.singleTrade(transactionInfo);
        }
        catch (CPException cpException)
        {
            log.error("银联单笔代付错误");
            return this.convertJsonObject(new SingleTradeResult(cpException.getErrno()));
        }
        return this.convertJsonObject(singleTradeResult);
    }

    /**
     * 单笔代付查询
     */
    @ApiOperation(value = "单笔代付查询", notes = "单笔代付查询")
    @PostMapping(value = "singleQuery")
    public SingleTradeResult singleQuery(@ApiParam(name = "singleQueryParam", value = "单笔代付查询信息") @RequestBody SingleQueryParam singleQueryParam) {
        SingleTradeResult singleTradeResult = null;
        try {
            singleTradeResult = singleTradeService.singleQuery(singleQueryParam);
        }
        catch (CPException cpException)
        {
            log.error("银联单笔代付查询错误");
            return new SingleTradeResult(cpException.getErrno());
        }

        return singleTradeResult;
    }

    /**
     * 处理返回结果
     */
    private JSONObject convertJsonObject(SingleTradeResult singleTradeResult) {
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(singleTradeResult));
        log.info(jsonObject.toJSONString());
        return jsonObject;
    }
}
